// 删除树结构中空的子节点
export const getSelectedNode = (arr, arrKey)=>{
  if (arr && arr.length) {
    arr.forEach((item) => {
      if (item[arrKey] && !item[arrKey].length) {
        delete item[arrKey]
      } else if (item[arrKey] && item[arrKey].length) {
        this.getSelectedNode(item[arrKey], arrKey)
      }
    })
  }
  return arr
  // 使用：let list = this.getSelectedNode(data,'children');
}
export const treeChange = (arr) =>{
  return arr.map(item => {
    if (item.children && item.children.length > 0) {
      this.treeChange(item.children)
    } else {
      delete item.children
    }
    return item
  })
}

// 图片格式转换：将base64转为file
export const dataURLtoFile = (dataurl, filename) =>{
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while(n--){
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, {type:mime});
}

// 压缩图片
export const afterRead = (file) =>{
  console.log(file)
  if (file instanceof Array == false) {
    file = [file]
  }
  file.forEach(item => {
    // 图片大于500kb就压缩  500*1024=512000
    if (item.file.size > 512000) {
      let canvas = document.createElement('canvas') // 创建Canvas对象(画布)
      let context = canvas.getContext('2d')
      let img = new Image()
      img.src = item.content // 指定图片的DataURL(图片的base64编码数据)
      img.onload = () => {
        canvas.width = img.naturalWidth / 4
        canvas.height = img.naturalHeight / 4
        context.drawImage(img, 0, 0, canvas.width, canvas.height)
        item.content = canvas.toDataURL(item.file.type, 0.92) // 0.92为默认压缩质量
        let myFile = this.dataURLtoFile(item.content, item.file.name)//dataURLtoFile为自己封装的函数，将base64转为file
        console.log("压缩后",myFile)
        var formDatas = new FormData()
        formDatas.append('fileName', myFile)
        console.log('大于500KB',formDatas);
        this.upload(formDatas)//上传的封装函数
      }
    } else { //小于500kb直接上传
      var formData = new FormData()
      formData.append('fileName', item.file)
      console.log("小于500KB",formData)
      this.upload(formData)//上传的封装函数
    }
  })
}